<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/3/4
 * Time: 19:44
 * Use :
 * File: Query.php
 */

namespace ulue\core\db\mysql\query;

use ulue\core\db\base\query\AbstractDataQuery;

class Query extends AbstractDataQuery
{
    protected $name = 'mysql';

    public function buildCreate(array $data, $table=null)
    {
        if (!$data)
        {
            throw new \DInvalidArgumentException('请传入需要构建创建语句的数据(array).');
        }

        $colStr = $valStr   = '';
        $table  = $table ? : $this->table;

        foreach($data as $column => $value)
        {
            $this->db->verifyColumn($column, $table);

            $colStr .= $this->quoteName($column) . ',';
            $valStr .= $this->quote($value) . ',';
        }

        $colStr = rtrim($colStr,', ');
        $valStr = rtrim($valStr,', ');

        $sql    = SqlBuilder::createRecord($table, $colStr, $valStr);

        return $sql;
    }

    public function buildUpdate(array $data, $table=null)
    {
        $table  = $table ? : $this->table;
        $string = '';

        foreach($data as $column=> $value)
        {
            $this->db->verifyColumn($column, $table);

            $column  = $this->quoteName($column);
            $value   = $this->quote($value);
            $string .= "$column=$value,";
        }

        $string = trim($string, ', ');
        return  SqlBuilder::updateRecord($table, $string, $this->where);
    }

    public function buildDelete($table=null)
    {
        $table = $table ? : $this->table;
        $where = trim($this->where);
        $condition = str_replace( ' ','', substr($where, 5) );

        if (!$where || $condition == 1  || $condition == '1=1' )//substr(trim($sql),0,1) == 1 ||
        {
            \Trigger::error('DELETE 语句，where条件不允许等于 1 或 没有where条件！');
        }

        return SqlBuilder::deleteRecord($table, $where);
    }

}// end class Query